using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using LiveStock.dataAccess;

namespace LiveStock
{
    public partial class ManageUser : FadeForm
    {
        bool isLogin = false; // used in determining what to do on closing this form
        bool isUpdate = false;
        CurrentUser curUser;
        private List<CurrentUser> usersList = new List<CurrentUser>(); //List to store users for use in deleting/updating users from combobox.
        
        //This constructor is to set UI settings for non-Admins 1
        public ManageUser(CurrentUser cur)
        {
            InitializeComponent();
            curUser = cur;

            setGUI(curUser.UserType, curUser.UserID);
        }

        #region Functions

        private void setGUI(int userType,int userID)
        {
            // User is not an Admin
            if (userType == 1)
            {
                this.Text = "My Account";
                Manage_cboUsers.Visible = false;
                Manage_lblUser.Visible = false;
                Manage_btnDelete.Enabled = true;
            }
            // User is an Admin
            else
            {
                this.Text = "User Management";
                Manage_cboUsers.Visible = true;
                Manage_lblUser.Visible = true;
                Manage_btnDelete.Enabled = false;

                //load users from DB into dropdown list
                usersList.Clear();
                Users.UsersDataTable udt = UsersData.GetUsers();
                Manage_cboUsers.Items.Clear();
                for (int u = 0; u < udt.Rows.Count; u++)
                {
                    CurrentUser temp = new CurrentUser(udt[u].UserID, udt[u].UserName, udt[u].Password, udt[u].FullName, udt[u].UserType);
                    usersList.Add(temp);
                    Manage_cboUsers.Items.Add(temp.UserName);
                }
            }

            //User Came from Login Screen
            if (userID == -1)
            {
                isLogin = true;
                Manage_txtUserName.ReadOnly = false;
                this.Text = "New User Creation";
                Manage_btnDelete.Enabled = false;
                Manage_cboUsers.Visible = false;
                Manage_lblUser.Visible = false;
            }
            // User came from within the app, load user information into the textboxes
            // if User is admin select index 0 on combobox wich will always be the current user
            // because method in DataAccessLayer sorts by UserType so UserType of 0 will be the first row.
            else
            {
                //Load the user information into the text boxes to allow for updating information on save.
                loadUserInfo(curUser.UserID);
                if (userType == 0)
                {
                    Manage_cboUsers.SelectedIndex = 0;
                }
                isUpdate = true;
            }  

        }

        private void loadUserInfo(int userID)
        {
            //Load the user information into the text boxes to allow for updating information on save.
            Users.UsersDataTable udt = UsersData.GetUserByID(userID);
            if (udt.Rows.Count > 0)
            {                
                Manage_txtUserName.ReadOnly = true;
                Manage_txtUserName.Text = udt[0].UserName;
                Manage_txtPassword.Text = udt[0].Password;
                Manage_txtFullName.Text = udt[0].FullName;
            }
            isUpdate = true;
        }
        private Boolean validateInput()
        {
            if (Manage_txtUserName.Text.Equals(""))
            {
                Manage_btnSave.Enabled = false;
                return false;
            }
            else if (Manage_txtPassword.Text.Equals(""))
            {
                Manage_btnSave.Enabled = false;
                return false;
            }
            else if (Manage_txtConfirm.Text.Equals("") || !Manage_txtConfirm.Text.Equals(Manage_txtPassword.Text))
            {
                Manage_btnSave.Enabled = false;
                return false;
            }
            else if (Manage_txtFullName.Text.Equals(""))
            {
                Manage_btnSave.Enabled = false;
                return false;
            }            
            else
            {
                Manage_btnSave.Enabled = true;
                return true;
            }

        }

        #endregion

        #region Buttons

        private void Manage_btnSave_Click(object sender, EventArgs e)
        {

            if (Manage_txtPassword.Text.Equals(Manage_txtConfirm.Text))
                {

                    if (isUpdate)
                    {
                        if (!Manage_cboUsers.Visible == true)
                        {
                            // Create a new table and row, set the values and run the UserUpdateByUserID
                            Users.UsersDataTable udt = new dataAccess.Users.UsersDataTable();
                            Users.UsersRow one = udt.NewUsersRow();

                            one.UserID = curUser.UserID;
                            one.UserName = curUser.UserName;
                            one.Password = Manage_txtPassword.Text;
                            one.FullName = Manage_txtFullName.Text;
                            one.UserType = curUser.UserType;

                            UsersData.UserUpdateByUserID(one);
                        }
                        else
                        {
                            // Create a new table and row, set the values and run the UserUpdateByUserID
                            Users.UsersDataTable udt = new dataAccess.Users.UsersDataTable();
                            Users.UsersRow one = udt.NewUsersRow();

                            one.UserID = usersList[Manage_cboUsers.SelectedIndex].UserID;
                            one.UserName = Manage_txtUserName.Text;
                            one.Password = Manage_txtPassword.Text;
                            one.FullName = Manage_txtFullName.Text;
                            one.UserType = usersList[Manage_cboUsers.SelectedIndex].UserType;
                        }


                        // Reset data for the current user, password changes will be observed on next login.
                        // the rest of the forms wont use the password until next login.
                        // Notifiy user that changes will take effect on next login.
                        MessageBox.Show("Changes will take effect upon next login.");
                    }
                    
                    else
                    {

                        try
                        {
                            //Create a new User row, set values
                            Users.UsersDataTable udt = new dataAccess.Users.UsersDataTable();
                            Users.UsersRow one = udt.NewUsersRow();

                            one.UserName = Manage_txtUserName.Text;
                            one.Password = Manage_txtPassword.Text;
                            one.FullName = Manage_txtFullName.Text;
                            one.UserType = curUser.UserType;  //default user should always be set to 1 unless no users are in the database, then 0


                            UsersData.UserInsert(one);


                            // If the user has come from the Login screen, then initiate & launch the MainForm as a NEW form.
                            // set the current UserID and Type to what is returned from UserLogin stored procedure.    
                            if (isLogin == true)
                            {
                                udt = UsersData.UserLogin(Manage_txtUserName.Text, Manage_txtPassword.Text);
                                if (udt.Rows.Count > 0)
                                {
                                    CurrentUser cur = new CurrentUser(udt[0].UserID, udt[0].UserName, udt[0].Password, udt[0].FullName, udt[0].UserType);
                                    KeywordsData.newUserDefaultKeywordsInsert(udt[0].UserID);
                                    MainForm main = new MainForm(cur);
                                    main.Show();
                                }
                            }

                            this.DialogResult = DialogResult.OK;
                        }
                        catch
                        {
                            DialogResult r = MessageBox.Show("You MUST have atleast SQL Server Express running/installed to use LiveStock\nLiveStock will now Exit.", "SQL?", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Application.Exit();
                        }
                        
                    }
                    if (!isLogin)
                    {
                        this.Hide();
                    }


                }
                else
                {
                    MessageBox.Show("Password and Confirm Password do not match.");
                    this.DialogResult = DialogResult.Ignore;
                }
            
            
        }


        private void Manage_cboUsers_SelectedIndexChanged(object sender, EventArgs e)
        {
            loadUserInfo(usersList[Manage_cboUsers.SelectedIndex].UserID);
            if (usersList[Manage_cboUsers.SelectedIndex].UserType != 0)
            {
                Manage_btnDelete.Enabled = true;
            }
            else { Manage_btnDelete.Enabled = false; }
        }

        private void Manage_btnDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you wish to Delete the User Account?\nAll User Information will be lost","Delete Account?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) 
            {
                if (Manage_cboUsers.Visible == false)
                {
                    UsersData.UserDeleteByID(curUser.UserID);
                    Application.Exit();
                }
                else
                {
                    UsersData.UserDeleteByID(usersList[Manage_cboUsers.SelectedIndex].UserID);
                    //load users from DB into dropdown list
                    usersList.Clear();
                    Users.UsersDataTable udt = UsersData.GetUsers();
                    Manage_cboUsers.Items.Clear();
                    for (int u = 0; u < udt.Rows.Count; u++)
                    {
                        CurrentUser temp = new CurrentUser(udt[u].UserID, udt[u].UserName, udt[u].Password, udt[u].FullName, udt[u].UserType);
                        usersList.Add(temp);
                        Manage_cboUsers.Items.Add(temp.UserName);
                    }
                    Manage_cboUsers.SelectedIndex = 0;
                    Manage_btnDelete.Enabled = false;

                }
            }
        }

        private void Manage_txtFullName_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Manage_btnSave.Focus();
                Manage_btnSave.PerformClick();
                e.Handled = true;
            }
        }

        #endregion

        #region GUI events

        private void Manage_txtUserName_TextChanged(object sender, EventArgs e)
        {
            validateInput();
        }

        private void Manage_txtPassword_TextChanged(object sender, EventArgs e)
        {
            validateInput();
        }

        private void Manage_txtConfirm_TextChanged(object sender, EventArgs e)
        {
            validateInput();
        }

        private void Manage_txtFullName_TextChanged(object sender, EventArgs e)
        {
            validateInput();
        }
        #endregion

        private void Manage_txtConfirm_Leave(object sender, EventArgs e)
        {
            if (!Manage_txtConfirm.Text.Equals(Manage_txtPassword.Text))
            {
                Manage_txtConfirm.Focus();
                label5.ForeColor = System.Drawing.Color.Red;
                MessageBox.Show("Password & Confirm Password do not match","Passwords Don't Match",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
                Manage_btnSave.Enabled = false;
            }
            else 
                label5.ForeColor = System.Drawing.Color.Black;
        }

        private void Manage_txtUserName_Leave(object sender, EventArgs e)
        {
            if (UsersData.UserAlreadyExists(Manage_txtUserName.Text) && !isUpdate)
            {
                MessageBox.Show("The user name you have selected is already in use.\nPlease select another.", "User Already Exists", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Manage_txtUserName.Focus();
                label1.ForeColor = Color.Red;
            }
            else
                label1.ForeColor = Color.Black;
        }
        
    }
}